package org.chend.customer;

import cn.hutool.core.lang.Validator;
import lombok.extern.slf4j.Slf4j;
import org.chend.customer.client.FraudService;
import org.chend.customer.exception.ApiException;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Slf4j
@Service
public record CustomerService(
        CustomerRepository customerRepository,
        FraudService fraudService) {

    public String registerCustomer(CustomerRegistryRequest request) {
        // 利用上面的参数构造一个Customer对象
        Customer customer = Customer.builder()
                .name(request.name())
                .email(request.email())
                .build();

        // 检查email是否有效
        if (request.email()==null|| !Validator.isEmail(request.email())) {
            log.error("new customer registration: email地址无效");
        }
        // 检查email是否已经注册
        // 提示：先思考如何编写sql，再考虑CustomerRepository中如何实现
        Optional<Customer> existEmail = customerRepository.findByEmail(customer.getEmail());
        if (!existEmail.isEmpty()) {
            // 注册失败
            log.info("new customer registration: 注册失败 {}, 邮箱已存在", customer);
            throw new ApiException("Email地址已经注册");
        }

        // 调用fraud服务，检查要注册的用户是否有征信问题
        Boolean fraudReviewResponse = fraudService.isFraudster(customer.getEmail());
        if (fraudReviewResponse) {
            throw new ApiException("用户存在征信问题");
        } else {
            // 存入数据库
            customerRepository.saveAndFlush(customer);
            // 发送通知
            log.info("new customer registration: 注册成功 {}", customer);
            return "注册成功";
        }
    }

    public void login(LoginRequest request) {
        Optional<Customer> existCustomer = customerRepository.findByNameAndEmail(request.name(), request.email());
        if (existCustomer.isEmpty()) {
            // 注册失败
            log.info("用户不存在");
            throw new ApiException("用户不存在");
        }
        log.info("用户登录成功");
    }
}
